<?php

namespace App\Exceptions;

use App\Lib\Logs\Logs;
use Exception;
use Flower\WeChatAuth\Exceptions\AuthApiException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class Handler extends ExceptionHandler
{
	private $statusCode;
	private $msg;
	private $errorCode;
	// 返回客户端当前请求的url路径
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

	/**
	 * @param Exception $exception
	 * @return mixed|void
	 * @throws Exception
	 */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
    	if($exception instanceof BaseException){
			//如果是自定义异常
	        $this->msg = $exception->msg;
	        $this->errorCode = $exception->errorCode;
	        $this->statusCode = 0;
		}elseif($exception instanceof UnauthorizedHttpException){
		    $this->msg = 'token 失效';
		    $this->errorCode = '10001';
		    $this->statusCode = -1;
	    }elseif ($exception instanceof AuthApiException){
            $this->msg = $exception->getMessage();
            $this->errorCode = $exception->getCode();
            $this->statusCode = 0;
        }
//    	elseif($exception instanceof QueryException){
//		    $this->msg = '服务器累了，请休息一会儿';
//		    $this->errorCode = '80001';
//		    $this->statusCode = 0;
//	    }
        else{
            if(config('app.debug')){
	            return parent::render($request, $exception);
	        }else{
		        $this->errorCode = 999;
		        $this->msg = "服务器内部错误，小主不必知道！";
	            $this->statusCode = 0;
	        }
	    }
        if(config('app.error_log')){
	        $logsContent = '错误发生文件：'. $exception->getfile(). '错误发生行数：'.$exception->getLine().' 报错信息：'.$exception->getMessage();
	        Logs::errorInfo($logsContent);
        }
    	$result = [
    		'msg' => $this->msg,
		    'error_code' => $this->errorCode,
		    'status'  => empty($this->statusCode) ? 0 : $this->statusCode,
	    ];
	    return response()->json($result, 200);
    }

}
